package com.sau.pixelcart.common.exception;

import com.sau.pixelcart.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;

@Slf4j
@RestControllerAdvice
public class GlobalException{

    //========================= 自定义异常处理 =========================
    @ExceptionHandler(BaseException.class)
    public Result handleBaseException(BaseException e) {
        log.error(" 业务异常: {}", e.getMessage());
        if (e instanceof AccountException) {
            return Result.unauthorized().setMessage(e.getMessage());
        }else if (e instanceof BusinessException) {
            return Result.error(e.getMessage());
        }
        return Result.error(e.getMessage());
    }


    // 权限异常处理
    @ExceptionHandler(AccessDeniedException.class)
    public Result handleAccessDeniedException() {
        log.warn(" 权限拒绝访问");
        return Result.forbidden().setMessage("您没有该操作权限");
    }

//    // 404处理（需配置spring.mvc.throw-exception-if-no-handler-found=true ）
//    @ExceptionHandler(NoHandlerFoundException.class)
//    public Result handleNotFoundException() {
//        return Result.notFound("请求资源失败");
//    }

//    // 数据库异常处理
//    @ExceptionHandler({DataIntegrityViolationException.class,  EmptyResultDataAccessException.class})
//    public Result handleDataException(Exception e) {
//        log.error(" 数据库操作异常: {}", e.getMessage());
//        return Result.businessError(" 数据操作失败，请检查数据合法性");
//    }

    //========================= 系统级异常处理 =========================
    // 兜底异常处理
    @ExceptionHandler(Exception.class)
    public Result handleGeneralException(Exception e) {
        log.error(" 系统异常: {}", e.getMessage());
        e.printStackTrace();
        return Result.serviceUnavailable(" 系统繁忙，请稍后再试");
    }

    // JSON解析异常
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result handleJsonParseException() {
        return Result.badRequest(" 请求体格式错误");
    }
}
